/*
 * Created by Federico Pisarello - SisDev Software (c) 2012 - fpisarello@sisdevsoft.com
 */

var popForm = 'foodsPop.php';
var actionForm = 'foodsAction.php';

var joDataFoods;
var oTable;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var action = undefined;

function $_init()
{
	$('#btnFoods').removeClass('btnMenu').addClass('btnMenuAct');
	
	var gaiSelected;
	
	$(document).ready(function() {
    	oTable = $('#dt_foods').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?actionOfForm=search",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					            null,
					  			null,
					  			null,
					  			{
					            	"sType": "numeric",
					            	"sClass": "textAlignRight",
					            	"fnRender": function (oObj) {    
					            		return RenderDecimalNumber(oObj);
					            	}
					            },
					            null
					             ]
					            
				});
    	
    	/* Click event handler */
    	$('#dt_foods tbody tr').live('click', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	        }
	        else {
	            oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	});
	});
	
	$("#foodsDialog").dialog({
		autoOpen:false, 
		height:380, 
		width:600, 
		dialogClass:'no-close',
		beforeClose: function() {$("#foodsDialog").empty();},
		open: function() {
			$('#foodsDialog').css('background','url(imagenes/bg.gif)');
			//Add Click for All Buttons in Pop Form
			$('#btnSave').click( function(e) {
				$('#foodsDialog').submit();
			});
		}
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAdd").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEdit').click( function(e) {
		editProxyShow();
	});
	
	$('#btnErase').click( function(e) {
		delProxyShow();
	});
}

function RenderDecimalNumber(oObj) {
	var num = new NumberFormat();    
	num.setInputDecimal('.');    
	num.setNumber(oObj.aData[oObj.iDataColumn]);     
	num.setPlaces(2, true);        
	num.setCurrency(true);     
	num.setNegativeFormat(num.LEFT_DASH);     
	return num.toFormatted();
}

function $_initPop()
{
	//Set Textbox Mask and Events
	$(".numeric").numeric();
	$("#foodPrice").blur(function(){   
		$(this).parseNumber({format:"####.00", locale:"us"});   
		$(this).formatNumber({format:"####.00", locale:"us"});
	});
	
	$('#btnExit').click( function(e) {
		$('#foodsDialog').dialog('close');
	});

	var idRestaurant;
	var idTypeFood;
	
	$_ValidatorSetDefaults();
	$_initPopValidator();
	
	//Populate User Data	
	if(action == iConst.EDIT)
	{
		$('#foodDescription').val(joDataFoods.description);
		$('#foodPrice').val(joDataFoods.price);
		idTypeFood = joDataFoods.idTypeFood;
		idRestaurant = joDataFoods.idRestaurant;
	}
		
	//Populate Combos
	if($('#cmbRestaurant').length > 0)
	{
		$.ajax({ 
		    url: actionForm, 
		    type:'POST', 
		    data: 'actionOfForm=getRestaurants', 
		    dataType: 'json', 
		    success: function(json) {
		    	$('#cmbRestaurant').append($('<option>').text('...').attr('value', 0));
		        $.each(json, function(i, value) {
		        	if(value.idRestaurant == idRestaurant)
		        		$('#cmbRestaurant').append($('<option selected>').text(value.businessName).attr('value', value.idRestaurant));
		        	else
		        		$('#cmbRestaurant').append($('<option>').text(value.businessName).attr('value', value.idRestaurant));
		        });
		        
		    	$('#cmbRestaurant').change( function() {
		    		//Clear combobox
		    		$("#cmbTypeFoods").html("");
		    		
		    		if($('#cmbRestaurant').val()!=0)
		    		{
			    		//Populate Combos
			    		$.ajax({ 
			    		    url: actionForm, 
			    		    type:'POST', 
			    		    data: 'actionOfForm=getTypeFoods&idRestaurant=' + $('#cmbRestaurant').val(), 
			    		    dataType: 'json', 
			    		    success: function(json) {
			    		    	$('#cmbTypeFoods').append($('<option>').text('...').attr('value', 0));
			    		        $.each(json, function(i, value) {
			    		        	if(value.idTypeFood == idTypeFood)
			    		        		$('#cmbTypeFoods').append($('<option selected>').text(value.description).attr('value', value.idTypeFood));
			    		        	else
			    		        		$('#cmbTypeFoods').append($('<option>').text(value.description).attr('value', value.idTypeFood));
			    		        });
			    		    }
			    		});
		    		}
		    	});
		    	
		    	//Call Event
		    	$('#cmbRestaurant').change();
		    	$("#foodPrice").blur();
		    }
		});
	}
	else
	{
		//Populate Combos
		$.ajax({ 
		    url: actionForm, 
		    type:'POST', 
		    data: 'actionOfForm=getTypeFoods', 
		    dataType: 'json', 
		    success: function(json) {
		    	$('#cmbTypeFoods').append($('<option>').text('...').attr('value', 0));
		        $.each(json, function(i, value) {
		        	if(value.idTypeFood == idTypeFood)
		        		$('#cmbTypeFoods').append($('<option selected>').text(value.description).attr('value', value.idTypeFood));
		        	else
		        		$('#cmbTypeFoods').append($('<option>').text(value.description).attr('value', value.idTypeFood));
		        });
		    }
		});
	}
}

function addProxyShow()
{
	//Reset State of action and IndexPK
	actionPK = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	$('#foodsDialog').load(popForm).dialog('open');
}

function editProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "actionOfForm=" + iConst.EDIT + "&idFood=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataFoods = jsonObj;
        						//Open Pop Dialog
        						$('#foodsDialog').load(popForm).dialog('open');
                            }
        });
	
return true;
}

function $_saveFood(action)
{
	var paramData = 'actionOfForm=addOrEdit&' + $("#foodsPopForm").serialize();
	
	if(action == iConst.EDIT)
		paramData += '&idFood=' + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#foodsDialog').dialog('close');
				oTable.fnReloadAjax();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });

return true;
}

function delProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deleteFoodsDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#deleteFoodsDialog').css('background','url(imagenes/bg.gif)');
			$('#btnConfirmDelete').click( function(e) {
				$_del();
			});
			$('#btnExitDelete').click( function(e) {
				$('#deleteFoodsDialog').dialog('close')
			})
		}
	});
	$('#deleteFoodsDialog').dialog('open');	
}

function $_del()
{
	var paramData = 'actionOfForm=' + action + '&idFood=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){
										$_showMessage('OK', 'OK', jsonObj.msg);
										
										//Reset State of action and IndexPK
										actionPK = undefined;
										action = iConst.NEW;
										oTable.fnReloadAjax();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deleteFoodsDialog').dialog('close');
                                }
            });

return true;
}

function $_initPopValidator()
{
	$('#foodsPopForm').validate({
		submitHandler: function() {
			$_saveFood(action);
		}, 		
		rules: {
			foodDescription: {required: true,minlength: 1},
			cmbTypeFoods: {required: true, minlength: 1},
			foodPrice: {required: true, minlength: 1}
		},
		messages: {
			foodDescription: {required: '',minlength: ''},
			cmbTypeFoods: {required: '',minlength: ''},
			foodPrice: {required: '',minlength: ''}
		}
	});
}